package com.example.bookstore.security.relam;

import com.example.bookstore.token.LoginToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
public class SysModularRealmAuthenticator extends ModularRealmAuthenticator {


    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        log.info("UserModularRealmAuthenticator:method doAuthenticate() execute ");
        // 判断getRealms()是否返回为空
        assertRealmsConfigured();
        // 强制转换回自定义的CustomizedToken
        LoginToken token = (LoginToken) authenticationToken;
        // 登录类型
        String loginType = token.getLoginType();
        // 所有Realm
        Collection<Realm> realms = getRealms();
        // 登录类型对应的所有Realm
        List<Realm> typeRealms = new ArrayList<>();
        for (Realm realm : realms) {
            if (realm.getName().contains(loginType)) {
                typeRealms.add (realm);
            }
        }

        // 判断是单Realm还是多Realm
        if (typeRealms.size() == 1){
            log.info("doSingleRealmAuthentication() execute ");
            return doSingleRealmAuthentication(typeRealms.get (0),token);
        }
        else{
            log.info("doMultiRealmAuthentication() execute ");
            return doMultiRealmAuthentication(typeRealms,token);
        }
    }
}
